package com.lhf.aicloud.controller;

import cn.hutool.jwt.JWTUtil;
import com.lhf.aicloud.entity.User;
import com.lhf.aicloud.entity.dto.UserDTO;
import com.lhf.aicloud.service.IUserService;
import com.lhf.aicloud.utils.NameUtil;
import com.lhf.aicloud.utils.ResponseEntity;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;

/**
 * @author : lhf
 * @date : Created in 2024/07/28
 */
@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {

    @Resource
    private RedisTemplate redisTemplate;

    @Resource
    private IUserService userService;

    @Resource
    private PasswordEncoder passwordEncoder;

    @Value("${jwt.secret}")
    private String jwtSecret;

    /**
     * 登录
     */
    @RequestMapping("/login")
    public ResponseEntity login(@Validated UserDTO userDTO, HttpServletRequest request) {
        // 校验图形验证码
        String redisCaptchaKey = NameUtil.getCaptchaName(request);
        String redisCaptchaValue = (String)redisTemplate.opsForValue().get(redisCaptchaKey);

        if (redisCaptchaValue == null || !redisCaptchaValue.equalsIgnoreCase(userDTO.getCaptcha())) {
            return ResponseEntity.error(400, "验证码错误");
        }

        // 验证用户名和密码
        User user = userService.lambdaQuery()
                .eq(User::getUsername, userDTO.getUsername()).one();
        // 对比加盐密码
        if (user != null && passwordEncoder.matches(userDTO.getPassword(), user.getPassword())) {
            // 生成 JWT
            HashMap<String, Object> payloads = new HashMap<>();
            payloads.put("uid", user.getUid());
            payloads.put("username", user.getUsername());
            String token = JWTUtil.createToken(payloads, jwtSecret.getBytes());
            HashMap<String, String> response = new HashMap<>();
            response.put("token", token);
            response.put("username", user.getNickname());
            return ResponseEntity.success(response);
        }
        return ResponseEntity.error(400, "用户名或密码错误");
    }

    /**
     * 注册功能
     */
    @RequestMapping("/register")
    public ResponseEntity register(@Validated User user) {

        // 查询一下有没有这个用户
        User tmpUser = userService.lambdaQuery().eq(User::getUsername, user.getUsername()).one();
        if (tmpUser != null) {
            return ResponseEntity.error(400, "该用户名已存在！");
        }
        // 对密码进行加盐处理
        user.setPassword(passwordEncoder.encode(user.getPassword()));
        // 添加用户
        boolean isSuccess = userService.save(user);
        if (!isSuccess) {
            return ResponseEntity.error(500, "未知错误！");
        }
        return ResponseEntity.success("注册成功");
    }

    @RequestMapping("/test")
    public ResponseEntity test() {
        return ResponseEntity.success("OK");
    }
}
